--this handles the events
EventManager = {}


--create the resource managers
EventManager.keyboard = {}
EventManager.keyboard.pressed = {}
EventManager.keyboard.released = {}


EventManager.mouse = {}
EventManager.mouse.motion = nil
EventManager.mouse.pressed = {}
EventManager.mouse.released = {}


--joystick handling is inherently difficult because there can be multiple joysticks
--thus, instead of having it be that the axis/button/etc... is the index for each,
-- the index is the joystick that the event originates from.
EventManager.joystick = {}
EventManager.joystick.axis_motion = {}
EventManager.joystick.ball_motion = {}
EventManager.joystick.hat_motion = {}
EventManager.joystick.pressed = {}
EventManager.joystick.released = {}

--misc events
EventManager.quit = nil


--state variables
EventManager.type = 0
EventManager.state = 0
EventManager.arg1 = 0
EventManager.arg2 = 0
EventManager.arg3 = 0
EventManager.arg4 = 0


--constructor
function EventManager:new(o)
  o = o or {}
  setmetatable(o, self)
  self.__index = self
  return o
end


--gets and evaluates events
function EventManager:gather_events()

  self.type, self.state, self.arg1, self.arg2, self.arg3, self.arg4 = get_event()

  while (self.type ~= 0) do

    --keyboard handling
    if self.type == "keyboard" then 
      if self.keyboard[self.state][self.arg1] then self.keyboard[self.state][self.arg1]() end

    --mouse handling
    elseif self.type == "mouse" then
      if self.state == "motion" then
        if self.mouse.motion then self.mouse.motion(self.arg1, self.arg2, self.arg3, self.arg4) end
      else
        if self.mouse[self.state][self.arg1] then self.mouse[self.state][self.arg1](self.arg2, self.arg3) end
      end

    --joystick handling
    elseif self.type == "joystick" then
      if self.state == "axis_motion" then 
        if self.joystick.axis_motion[self.arg1] then self.joystick.axis_motion[self.arg1](self.arg2, self.arg3) end
      elseif self.state == "ball_motion" then
        if self.joystick.ball_motion[self.arg1] then self.joystick.ball_motion[self.arg1](self.arg2, self.arg3, self.arg4) end
      elseif self.state == "hat_motion" then
        if self.joystick.hat_motion[self.arg1] then self.joystick.hat_motion[self.arg1](self.arg2, self.arg3) end
      else
        if self.joystick[self.state][self.arg1] then self.joystick[self.state][self.arg1](self.arg2) end
      end 
      
    --misc events
    elseif self.type == "quit" then
      if self.quit then self.quit() end
    end
    
    self.type, self.state, self.arg1, self.arg2, self.arg3, self.arg4 = get_event()
  end

end
